package net.zjitc.servlet;

import net.zjitc.domain.User;
import net.zjitc.service.UserService;
import net.zjitc.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author admin
 * @Date 2019/3/5 8:53
 */
@WebServlet(name = "RegisterServlet",urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        User user = new User();
        UserService service = new UserServiceImpl();
        String username = request.getParameter("username");
        String pwd = request.getParameter("password");
        String pwd1 = request.getParameter("password1");
        User user1 = service.findByUsername(username);
        if (user1 == null && pwd.equals(pwd1)){
            try {
                BeanUtils.populate(user,request.getParameterMap());
                service.add(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String path = request.getContextPath();
            response.sendRedirect(path+"/findDetail");
        }else if(!pwd.equals(pwd1)){
            request.setAttribute("pwdMsg","两次密码不同，请重新输入！");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }else{
            request.setAttribute("msg","用户名已存在！");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }

    }
}
